package com.itaem.community.core.advice;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itaem.community.core.annotations.ResponseResult;
import com.itaem.community.core.entity.Result;
import com.itaem.community.core.enums.ResultEnum;
import com.itaem.community.core.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <p>项目名称: community </p>
 * <p>文件名称: ResponseAdvice </p>
 * <p>描述: [类型描述] </p>
 * <p>创建时间: 2020/10/13 </p>
 * <p>作者信息: tomato</p>
 *
 * @author tomato
 * @version v1.0
 */
@Slf4j
@Component
@RestControllerAdvice(annotations = ResponseResult.class)
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        log.info("正在包装返回值...");

        // 提取分页信息
        if (body == null) {
            log.warn("无返回数据");
            return Result.success().setMessage("不存在数据");
        } else if (body instanceof Page) {
            log.info("分页数据 Page");
            return Result.success(PageUtils.extract((Page) body));
        } else if (body instanceof Result) {
            log.info("包装数据 Result");
            return body;
        } else if (body instanceof String) {
            log.info("字符串数据 String");
            return JSON.toJSONString(Result.success(body));
        } else if (body instanceof Boolean) {
            log.info("布尔二元结果 Boolean");
            if (Boolean.TRUE.equals(body)) {
                return Result.success(ResultEnum.OK);
            } else {
                return Result.failure(ResultEnum.FAIL);
            }
        } else if (body instanceof ResponseEntity) {
            log.info("Spring响应体 ResponseEntity");
            return body;
        }
        log.info("普通数据 NormalData");
        return Result.success(body);
    }
}


